#!/usr/bin/env python
#-*-coding:utf-8-*-
# ---------------------------------
# version:  1.0
#
# create-time:      <2008/12/03 02:53:25>
# last-update-time: <halida 12/21/2008 21:47:34>
# ---------------------------------
# module : entity list
# list entities to user


from qtlib import *

import entity

class EntityList(QWidget):
    """list entities in the pool,filted and sorted."""
    def __init__(self,pool):
        QListWidget.__init__(self)
        self.pool=pool
        self.list=[]
        self.tags=set([entity.NOW])
        self.filter = lambda e:e.hasTags(self.tags)
        self.sorter = lambda e:e.level
        self.reverse = True
        #component
        self.listView = QListWidget()
        self.input = QLineEdit()
        self.setAction()
        #layout
        l = QVBoxLayout(self)
        l.addWidget(self.input)
        l.addWidget(self.listView)
        #event
        conn(self.input,"returnPressed()",self.add)
        conn(self.pool,entity.POOL_CHANGED,self.refresh)
        conn(self.listView,"currentRowChanged(int)",self.select)

    #---update---
    def refresh(self,id=None):
        #only refresh one
        if id != None:
            for index,e in enumerate(self.list):
                if e.id==id:
                    #change name
                    name = self.pool.get(id).name
                    self.listView.item(index).setText(name)
                    #check exists in list
                    if not e.hasTags(self.tags):
                        item = self.listView.takeItem(index)
                        del item
                        self.list.pop(index)
                    return
        #refresh all
        logging.info("refreshing:%s" , ",".join(self.tags))
        if self.tags==None:
            self.list = list(self.pool.get())
        else:
            self.list = list(
                self.pool.get(func = self.filter))
        #sort
        self.list.sort(key=self.sorter,reverse=self.reverse)
        #check need update list when id specified
        self.refreshList()

    def refreshList(self):
        self.listView.clear()
        for entity in self.list:
            self.listView.addItem(entity.name)

    def select(self,index):
        if index<0:return
        if index>=len(self.list):return
        id = self.list[index].id
        emit(self,"selected",id)

    def changeTags(self,tags=None):
        self.tags = tags
        self.refresh()

    #---action---
    def setAction(self):
        #action list
        actions = (
            ("level &Up"  ,lambda:self.edit(lambda e:e.levelUp())),
            ("level &Down",lambda:self.edit(lambda e:e.levelDown())),
            ("-"*20       ,lambda:None),
            ("&Now"       ,lambda:self.edit(lambda e:e.addTag(entity.NOW))),
            ("&Later"     ,lambda:self.edit(lambda e:e.addTag(entity.LATER))),
            ("&Done"      ,lambda:self.edit(lambda e:e.addTag(entity.DONE))),
            ("&Reference" ,lambda:self.edit(lambda e:e.addTag(entity.REFERENCE))),
            ("-"*20       ,lambda:None),
            ("&split"     ,lambda:self.edit(lambda e:self.pool.split(e))),
            ("-"*20       ,lambda:None),
            ("&Delete"    ,self.deleteEntity),
            )
        #set
        self.listView.setContextMenuPolicy(Qt.ActionsContextMenu)
        for title,func in actions:
            action = QAction(title,self)
            conn(action,"triggered()",func)
            self.listView.addAction(action)

    def add(self):
        text = self.input.text()
        if text!="":
            e = self.pool.add(text)
            e.addTag(entity.NOW)
            e.addTags(self.tags)
            self.input.clear()
            self.refresh()

    def get(self):
        row = self.listView.currentRow()
        if row<0:return        
        return self.list[row]

    def edit(self,func):
        e = self.get()
        if e==None:return
        func(e)
        e.updateTime = datetime.now()
        self.refresh()

    def deleteEntity(self):
        e = self.get()
        if e==None:return
        self.pool.remove(e.id)
        self.refresh()

